import { app, BrowserWindow, ipcMain, dialog,Menu  } from "electron";
import path from "path";
import DataStore from "../renderer/MusicDataStore";

let myStore = new DataStore({ name: "Music Data" });

// 使用electron - store;
// const Store = require("electron-store");
// const store = new Store();
// // 使用点表示法访问嵌套属性
// store.set("foo.bar", true);
// console.log(store.get("foo")); //=> {bar: true}
// console.log(app.getPath("userData"));

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== "development") {
  global.__static = require("path")
    .join(__dirname, "/static")
    .replace(/\\/g, "\\\\");
}

let mainWindow;
let addMusicWindow;
const winURL =
  process.env.NODE_ENV === "development"
    ? `http://localhost:9080`
    : `file://${__dirname}/index.html`;

function createWindow() {
  /**
   * Initial window options
   */
  mainWindow = new BrowserWindow({
    show: false,
    icon: path.join(__dirname, "assets/logo2.png"),
    height: 563,
    useContentSize: true,
    width: 1000,
  });
  mainWindow.loadURL(winURL);
  mainWindow.once("ready-to-show", () => {
    mainWindow.show();
  });
  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (mainWindow === null) {
    createWindow();
  }
});

//添加音乐窗口
ipcMain.on("addMusic", (event, arg) => {
  addMusicWindow = new BrowserWindow({
    icon: path.join(__dirname, "assets/logo2.png"),
    height: 400,
    width: 600,
    webPreferences: {
      nodeIntegration: true,
    },
    parent: mainWindow,
  });
  addMusicWindow.loadURL(winURL + "#/add");
});

//选择音乐按钮--打开弹框dialog 
ipcMain.on("openMusicFile", (event) => {
  dialog.showOpenDialog(
    {
      properties: ["openFile", "multiSelections"],
      filters: [{ name: "Music", extensions: ["mp3"] }],
    },
    (files) => {
      if (files) {
        console.log('files',files);
        event.sender.send("dialogReply", files);
      }
    }
  );
});

ipcMain.on("improtMusic", (event, tracks) => {
  const updatedTracks = myStore.addTracks(tracks).getTracks();
  console.log(updatedTracks);
  addMusicWindow.hide();
  mainWindow.send("getTracks", updatedTracks);
});


//菜单设置
let template = [{
  label: '设置',
  submenu:[{
    role: 'reload'
  },
  {
    type: 'separator'
  },{
    role: 'close' 
  },
  {
    type: 'separator'
  },
  {role: 'togglefullscreen'
  }],
}];

//添加到ready调用的函数中
let menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);